package Object.work;

import Object.work.exception.*;
import Object.work.model.*;
import Object.work.service.LibraryService;
import Object.work.service.LibraryServiceImpl;

import java.util.List;
import java.util.Scanner;

public class Main {
    private static LibraryService libraryService = new LibraryServiceImpl(new Library());
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        // 初始化一些测试数据
        initializeSampleData();

        // 显示主菜单
        showMainMenu();
    }

    private static void initializeSampleData() {
        try {
            // 添加初始用户
            libraryService.addUser(new User("U001", "Admin", "admin@library.com"));
            libraryService.addUser(new User("U002", "张三", "zhangsan@example.com"));
            libraryService.addUser(new User("U003", "李四", "lisi@example.com"));

            // 添加初始图书
            libraryService.addBook(new PhysicalBook("B001", "Java编程思想", 2019, "Bruce Eckel", "9787111213826", "A101"));
            libraryService.addBook(new EBook("B002", "Python基础教程", 2020, "Magnus Lie Hetland", "9787115474889", "PDF", 8.5));
            libraryService.addBook(new PhysicalBook("B003", "设计模式", 2021, "Erich Gamma", "9787111643727", "B205"));
        } catch (DuplicateBookException e) {
            System.out.println("初始化数据时出错: " + e.getMessage());
        }
    }

    private static void showMainMenu() {
        while (true) {
            System.out.println("\n===== 图书管理系统主菜单 =====");
            System.out.println("1. 图书管理");
            System.out.println("2. 用户管理");
            System.out.println("3. 借还书管理");
            System.out.println("4. 查询统计");
            System.out.println("0. 退出系统");
            System.out.print("请选择功能(0-4): ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入数字！");
                continue;
            }

            switch (choice) {
                case 1:
                    showBookManagementMenu();
                    break;
                case 2:
                    showUserManagementMenu();
                    break;
                case 3:
                    showBorrowReturnMenu();
                    break;
                case 4:
                    showSearchStatisticsMenu();
                    break;
                case 0:
                    System.out.println("感谢使用图书管理系统，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void showBookManagementMenu() {
        while (true) {
            System.out.println("\n===== 图书管理 =====");
            System.out.println("1. 添加图书");
            System.out.println("2. 修改图书");
            System.out.println("3. 删除图书");
            System.out.println("4. 查看所有图书");
            System.out.println("5. 根据ID查询图书");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择功能(0-5): ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入数字！");
                continue;
            }

            switch (choice) {
                case 1:
                    addBook();
                    break;
                case 2:
                    updateBook();
                    break;
                case 3:
                    deleteBook();
                    break;
                case 4:
                    libraryService.displayAllBooks();
                    break;
                case 5:
                    searchBookById();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void addBook() {
        System.out.println("\n===== 添加图书 =====");
        System.out.println("1. 添加纸质书");
        System.out.println("2. 添加电子书");
        System.out.print("请选择图书类型(1-2): ");

        int typeChoice;
        try {
            typeChoice = Integer.parseInt(scanner.nextLine());
        } catch (NumberFormatException e) {
            System.out.println("输入无效，请输入数字！");
            return;
        }

        try {
            System.out.print("请输入图书ID: ");
            String id = scanner.nextLine();
            System.out.print("请输入图书标题: ");
            String title = scanner.nextLine();
            System.out.print("请输入出版年份: ");
            int year = Integer.parseInt(scanner.nextLine());
            System.out.print("请输入作者: ");
            String author = scanner.nextLine();
            System.out.print("请输入ISBN: ");
            String isbn = scanner.nextLine();

            if (typeChoice == 1) {
                System.out.print("请输入存放位置: ");
                String location = scanner.nextLine();
                PhysicalBook book = new PhysicalBook(id, title, year, author, isbn, location);
                libraryService.addBook(book);
                System.out.println("纸质书添加成功！");
            } else if (typeChoice == 2) {
                System.out.print("请输入文件格式: ");
                String format = scanner.nextLine();
                System.out.print("请输入文件大小(MB): ");
                double size = Double.parseDouble(scanner.nextLine());
                EBook book = new EBook(id, title, year, author, isbn, format, size);
                libraryService.addBook(book);
                System.out.println("电子书添加成功！");
            } else {
                System.out.println("无效选择！");
            }
        } catch (NumberFormatException e) {
            System.out.println("输入格式错误，请确保年份和大小为数字！");
        } catch (DuplicateBookException e) {
            System.out.println("添加失败: " + e.getMessage());
        }
    }

    private static void updateBook() {
        System.out.println("\n===== 修改图书 =====");
        libraryService.displayAllBooks();
        System.out.print("请输入要修改的图书ID: ");
        String id = scanner.nextLine();

        try {
            LibraryItem oldBook = libraryService.getBookById(id);
            System.out.println("当前图书信息: " + oldBook);

            System.out.print("请输入新图书ID(直接回车不修改): ");
            String newId = scanner.nextLine();
            if (newId.isEmpty()) newId = oldBook.getId();

            System.out.print("请输入新标题(直接回车不修改): ");
            String newTitle = scanner.nextLine();
            if (newTitle.isEmpty()) newTitle = oldBook.getTitle();

            System.out.print("请输入新出版年份(直接回车不修改): ");
            String yearStr = scanner.nextLine();
            int newYear = yearStr.isEmpty() ? oldBook.getYear() : Integer.parseInt(yearStr);

            if (oldBook instanceof PhysicalBook) {
                PhysicalBook physicalBook = (PhysicalBook) oldBook;
                System.out.print("请输入新作者(直接回车不修改): ");
                String newAuthor = scanner.nextLine();
                if (newAuthor.isEmpty()) newAuthor = physicalBook.getAuthor();

                System.out.print("请输入新ISBN(直接回车不修改): ");
                String newIsbn = scanner.nextLine();
                if (newIsbn.isEmpty()) newIsbn = physicalBook.getIsbn();

                System.out.print("请输入新存放位置(直接回车不修改): ");
                String newLocation = scanner.nextLine();
                if (newLocation.isEmpty()) newLocation = physicalBook.getLocation();

                PhysicalBook newBook = new PhysicalBook(newId, newTitle, newYear, newAuthor, newIsbn, newLocation);
                libraryService.updateBook(id, newBook);
                System.out.println("纸质书修改成功！");
            } else if (oldBook instanceof EBook) {
                EBook eBook = (EBook) oldBook;
                System.out.print("请输入新作者(直接回车不修改): ");
                String newAuthor = scanner.nextLine();
                if (newAuthor.isEmpty()) newAuthor = eBook.getAuthor();

                System.out.print("请输入新ISBN(直接回车不修改): ");
                String newIsbn = scanner.nextLine();
                if (newIsbn.isEmpty()) newIsbn = eBook.getIsbn();

                System.out.print("请输入新文件格式(直接回车不修改): ");
                String newFormat = scanner.nextLine();
                if (newFormat.isEmpty()) newFormat = eBook.getFormat();

                System.out.print("请输入新文件大小(MB)(直接回车不修改): ");
                String sizeStr = scanner.nextLine();
                double newSize = sizeStr.isEmpty() ? eBook.getFileSize() : Double.parseDouble(sizeStr);

                EBook newBook = new EBook(newId, newTitle, newYear, newAuthor, newIsbn, newFormat, newSize);
                libraryService.updateBook(id, newBook);
                System.out.println("电子书修改成功！");
            }
        } catch (BookNotFoundException e) {
            System.out.println("错误: " + e.getMessage());
        } catch (NumberFormatException e) {
            System.out.println("输入格式错误，请确保年份和大小为数字！");
        } catch (DuplicateBookException e) {
            System.out.println("修改失败: " + e.getMessage());
        }
    }

    private static void deleteBook() {
        System.out.println("\n===== 删除图书 =====");
        libraryService.displayAllBooks();
        System.out.print("请输入要删除的图书ID: ");
        String id = scanner.nextLine();

        try {
            libraryService.deleteBook(id);
            System.out.println("图书删除成功！");
        } catch (BookNotFoundException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }

    private static void searchBookById() {
        System.out.println("\n===== 根据ID查询图书 =====");
        System.out.print("请输入图书ID: ");
        String id = scanner.nextLine();

        try {
            LibraryItem book = libraryService.getBookById(id);
            System.out.println("查询结果: " + book);
        } catch (BookNotFoundException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }

    private static void showUserManagementMenu() {
        while (true) {
            System.out.println("\n===== 用户管理 =====");
            System.out.println("1. 添加用户");
            System.out.println("2. 修改用户");
            System.out.println("3. 删除用户");
            System.out.println("4. 查看所有用户");
            System.out.println("5. 根据ID查询用户");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择功能(0-5): ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入数字！");
                continue;
            }

            switch (choice) {
                case 1:
                    addUser();
                    break;
                case 2:
                    updateUser();
                    break;
                case 3:
                    deleteUser();
                    break;
                case 4:
                    libraryService.displayAllUsers();
                    break;
                case 5:
                    searchUserById();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void addUser() {
        System.out.println("\n===== 添加用户 =====");
        try {
            System.out.print("请输入用户ID: ");
            String id = scanner.nextLine();
            System.out.print("请输入用户姓名: ");
            String name = scanner.nextLine();
            System.out.print("请输入用户邮箱: ");
            String email = scanner.nextLine();

            User user = new User(id, name, email);
            libraryService.addUser(user);
            System.out.println("用户添加成功！");
        } catch (DuplicateBookException e) {
            System.out.println("添加失败: " + e.getMessage());
        }
    }

    private static void updateUser() {
        System.out.println("\n===== 修改用户 =====");
        libraryService.displayAllUsers();
        System.out.print("请输入要修改的用户ID: ");
        String id = scanner.nextLine();

        try {
            User oldUser = libraryService.getUserById(id);
            System.out.println("当前用户信息: " + oldUser);

            System.out.print("请输入新用户ID(直接回车不修改): ");
            String newId = scanner.nextLine();
            if (newId.isEmpty()) newId = oldUser.getId();

            System.out.print("请输入新姓名(直接回车不修改): ");
            String newName = scanner.nextLine();
            if (newName.isEmpty()) newName = oldUser.getName();

            System.out.print("请输入新邮箱(直接回车不修改): ");
            String newEmail = scanner.nextLine();
            if (newEmail.isEmpty()) newEmail = oldUser.getEmail();

            User newUser = new User(newId, newName, newEmail);
            libraryService.updateUser(id, newUser);
            System.out.println("用户修改成功！");
        } catch (UserNotFoundException e) {
            System.out.println("错误: " + e.getMessage());
        } catch (DuplicateBookException e) {
            System.out.println("修改失败: " + e.getMessage());
        }
    }

    private static void deleteUser() {
        System.out.println("\n===== 删除用户 =====");
        libraryService.displayAllUsers();
        System.out.print("请输入要删除的用户ID: ");
        String id = scanner.nextLine();

        try {
            libraryService.deleteUser(id);
            System.out.println("用户删除成功！");
        } catch (UserNotFoundException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }

    private static void searchUserById() {
        System.out.println("\n===== 根据ID查询用户 =====");
        System.out.print("请输入用户ID: ");
        String id = scanner.nextLine();

        try {
            User user = libraryService.getUserById(id);
            System.out.println("查询结果: " + user);
        } catch (UserNotFoundException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }

    private static void showBorrowReturnMenu() {
        while (true) {
            System.out.println("\n===== 借还书管理 =====");
            System.out.println("1. 借书");
            System.out.println("2. 还书");
            System.out.println("3. 查看可借阅图书");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择功能(0-3): ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入数字！");
                continue;
            }

            switch (choice) {
                case 1:
                    borrowBook();
                    break;
                case 2:
                    returnBook();
                    break;
                case 3:
                    showAvailableBooks();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void borrowBook() {
        System.out.println("\n===== 借书 =====");
        libraryService.displayAllUsers();
        System.out.print("请输入用户ID: ");
        String userId = scanner.nextLine();

        showAvailableBooks();
        System.out.print("请输入图书ID: ");
        String bookId = scanner.nextLine();

        try {
            libraryService.borrowBook(bookId, userId);
            System.out.println("借书成功！");
        } catch (BookNotFoundException | UserNotFoundException | InvalidOperationException e) {
            System.out.println("借书失败: " + e.getMessage());
        }
    }

    private static void returnBook() {
        System.out.println("\n===== 还书 =====");
        System.out.print("请输入图书ID: ");
        String bookId = scanner.nextLine();

        try {
            libraryService.returnBook(bookId);
            System.out.println("还书成功！");
        } catch (BookNotFoundException | InvalidOperationException e) {
            System.out.println("还书失败: " + e.getMessage());
        }
    }

    private static void showAvailableBooks() {
        System.out.println("\n===== 可借阅图书 =====");
        List<LibraryItem> allBooks = libraryService.getAllBooks();
        List<LibraryItem> availableBooks = allBooks.stream()
                .filter(book -> {
                    if (book instanceof PhysicalBook) {
                        return ((PhysicalBook) book).isAvailable();
                    }
                    return false;
                })
                .toList();

        if (availableBooks.isEmpty()) {
            System.out.println("当前没有可借阅的图书");
        } else {
            libraryService.displayBooks(availableBooks);
        }
    }

    private static void showSearchStatisticsMenu() {
        while (true) {
            System.out.println("\n===== 查询统计 =====");
            System.out.println("1. 按标题搜索图书");
            System.out.println("2. 按姓名搜索用户");
            System.out.println("3. 统计图书总数");
            System.out.println("4. 统计用户总数");
            System.out.println("0. 返回主菜单");
            System.out.print("请选择功能(0-4): ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("输入无效，请输入数字！");
                continue;
            }

            switch (choice) {
                case 1:
                    searchBooksByTitle();
                    break;
                case 2:
                    searchUsersByName();
                    break;
                case 3:
                    System.out.println("图书总数: " + libraryService.getAllBooks().size());
                    break;
                case 4:
                    System.out.println("用户总数: " + libraryService.getAllUsers().size());
                    break;
                case 0:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void searchBooksByTitle() {
        System.out.println("\n===== 按标题搜索图书 =====");
        System.out.print("请输入搜索关键词: ");
        String keyword = scanner.nextLine();

        List<LibraryItem> results = libraryService.searchBooksByTitle(keyword);
        libraryService.displayBooks(results);
    }

    private static void searchUsersByName() {
        System.out.println("\n===== 按姓名搜索用户 =====");
        System.out.print("请输入搜索关键词: ");
        String keyword = scanner.nextLine();

        List<User> results = libraryService.searchUsersByName(keyword);
        libraryService.displayUsers(results);
    }
}